package cn.hy.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hy.dto.UserDto;
import cn.hy.entity.SecKillUser;
import cn.hy.entity.SecKillUserExample;
import cn.hy.mapper.SecKillUserMapper;
import cn.hy.redis.key.UserKey;
import cn.hy.util.JwtTokenUtils;
import cn.hy.util.MD5Utils;
import cn.hy.vo.UserVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
public class UserServiceImpl implements UserService {


    @Resource
    private SecKillUserMapper secKillUserMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String login(UserVo userVo) {
        String mobile = userVo.getNickName();
        String password = userVo.getPassword();
        SecKillUser user = findByNickName(mobile);
        if (user == null) {
            throw new RuntimeException("user is not exist");
        }
        String dbPass = user.getPassword();
        String saltDb = user.getSalt();
        String calcPass = MD5Utils.formPassToDBPass(password, saltDb);
        if (!calcPass.equals(dbPass)) {
            throw new RuntimeException("password is not correct");
        }
        //生成cookie 将session返回游览器 分布式session
        String token = JwtTokenUtils.createToken(user.getNickname(), String.valueOf(user.getId()));
        stringRedisTemplate.opsForValue().set(UserKey.TOKEN.getKey(), token,
                UserKey.TOKEN.expireSeconds(), TimeUnit.SECONDS);
        return token;
    }

    @Override
    public boolean signUp(UserVo userVo) {
        SecKillUser secKillUser = new SecKillUser();
        secKillUser.setNickname(userVo.getNickName());
        //password  应该在前段进行一次MD5 在后端在进行一个MD5 在入库
        String salt = MD5Utils.getSaltT();
        String DBPassWord = MD5Utils.formPassToDBPass(userVo.getPassword(), salt);
        secKillUser.setPassword(DBPassWord);
        secKillUser.setRegisterDate(LocalDateTime.now());
        secKillUser.setSalt(salt);
        return secKillUserMapper.insert(secKillUser) > 1;
    }

    @Override
    public UserDto getById(Long id) {
        SecKillUser secKillUser = secKillUserMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(secKillUser, UserDto.class);
    }

    private SecKillUser findByNickName(String nickName) {
        SecKillUserExample example = new SecKillUserExample();
        example.createCriteria().andNicknameEqualTo(nickName);
        List<SecKillUser> secKillUsers = secKillUserMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(secKillUsers)) {
            throw new RuntimeException("user is not exist");
        }
        return secKillUsers.get(0);
    }
}
